package com.shunda.ysdgj.common.util;

import com.shunda.ysdgj.model.entity.system.SysMenu;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MenuUtil {

    public static List<SysMenu> getTreeMenu(List<SysMenu> menuList) {
        List<SysMenu> treeMenuList = new ArrayList<>();
        if (menuList.isEmpty()) {
            return treeMenuList;
        }
        if (menuList.size() == 1) {
            treeMenuList.add(menuList.get(0));
            return treeMenuList;
        }
        for (SysMenu menu : menuList) {
            if (menu.getParentId() == 0) {
                treeMenuList.add(getChildren(menu, menuList));
            }
        }
        return treeMenuList;
    }

    private static SysMenu getChildren(SysMenu parentMenu, List<SysMenu> menuList) {
        parentMenu.setChildren(new ArrayList<>());
        for (SysMenu menu : menuList) {
            if (Objects.equals(menu.getParentId(), parentMenu.getId())) {
                parentMenu.getChildren().add(getChildren(menu, menuList));
            }
        }
        return parentMenu;
    }

}
